package com.teamclub.util.files;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.io.Files;
import com.teamclub.util.libs.Libs;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.*;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Map;

/**
 * Created by ilkkzm on 17-9-25.
 */
public class ExcelExporter {
    private List<String> title;
    private List<String> keys;
    private List<Map<String,Object>> content;
    private File exporterFile;
    private XSSFWorkbook wb = null;
    private XSSFSheet sheet = null;
    public ExcelExporter(String fileName, String sheetName, List<String> title, List<String> keys, List<Map<String, Object>> content) {
        this.exporterFile = Libs.getTempFile(fileName);
        this.wb = new XSSFWorkbook();
        this.sheet = wb.createSheet(sheetName);
        this.title = title;
        this.keys = keys;
        this.content = content;

    }
    private void writeTitle() {
        XSSFCellStyle style = wb.createCellStyle();
        XSSFFont boldFont = wb.createFont();
        boldFont.setBold(true);
        style.setFont(boldFont);
        XSSFRow row = sheet.createRow(0);
        row.setRowStyle(style);
        for(int c = 0; c < title.size() ; c++) {
            XSSFCell cell = row.createCell(c);
            cell.setCellValue(title.get(c));
        }
    }
    private void writeContent() {
        for(int r = 0 ; r < content.size(); r++) {
            Map<String, Object> data = content.get(r);
            XSSFRow row = sheet.createRow(r + 1);
            for(int c = 0 ; c < keys.size(); c++) {
                XSSFCell cell = row.createCell(c);
                String key = keys.get(c);
                cell.setCellValue(data.get(key) + "");
            }
        }
    }


    public File downLoad() throws Exception {
        this.writeTitle();
        this.writeContent();
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(exporterFile);
            wb.write(fileOut);
            return exporterFile;
        } finally {
            fileOut.flush();
            fileOut.close();
            wb.close();
        }
    }

    public static void main(String[] args) throws Exception{
        ExcelExporter instance = new ExcelExporter("haha.xls",
                "销售报表",
                Lists.newArrayList("第一个", "第二个"),
                Lists.newArrayList("first", "second"),
                Lists.newArrayList(ImmutableMap.of("first", "AAA", "second", "BBB"))
                );
        File file = instance.downLoad();
        System.out.println(file.getAbsolutePath());
    }
}
